<template>
  <div ref="chartDom" class="pie-chart"></div>
</template>

<script setup>
import { onMounted, ref, watch } from 'vue';
import * as echarts from 'echarts';

const props = defineProps({
  chartData: {
    type: Array,
    required: true
  }
});

const chartDom = ref(null);
let myChart = null;

const initChart = () => {
  if (!props.chartData.length) return;
  
  if (myChart) {
    myChart.dispose();
  }
  
  myChart = echarts.init(chartDom.value);

  const option = {
    title: {
      text: '图书类型占比',
      left: 'center',
      textStyle: {
        fontSize: 16,
        fontWeight: 'bold'
      }
    },
    tooltip: {
      trigger: 'item',
      formatter: "{a} <br/>{b}: {c} ({d}%)"
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      data: props.chartData.map(item => item.name)
    },
    series: [
      {
        name: '图书类型占比',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: true,
        label: {
          show: true,
          position: 'outside',
          formatter: '{b}: {d}%'
        },
        labelLine: {
          show: true
        },
        data: props.chartData
      }
    ]
  };

  myChart.setOption(option);

  window.addEventListener('resize', function () {
    myChart.resize();
  });
};

onMounted(() => {
  initChart();
});

watch(() => props.chartData, () => {
  initChart();
}, { deep: true });
</script>

<style scoped>
.pie-chart {
  width: 100%;
  height: 400px;
  min-width: 300px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}
</style>